from django.contrib import admin
from django.contrib.auth.models import User
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from .models import UserProfile

# Register your models here.

class UserProfileInline(admin.StackedInline):
    """用户扩展信息内联编辑"""
    model = UserProfile
    can_delete = False
    fk_name = 'user'  # 指定使用user字段作为外键关联
    verbose_name = '扩展信息'
    verbose_name_plural = '扩展信息'
    fields = ('supervisor', 'phone', 'department', 'position', 'employee_id', 'hire_date', 'remarks')
    
class CustomUserAdmin(BaseUserAdmin):
    """自定义用户管理界面"""
    inlines = (UserProfileInline,)
    list_display = ('username', 'email', 'first_name', 'last_name', 'get_department', 'get_supervisor', 'is_staff')
    list_filter = ('is_staff', 'is_superuser', 'is_active', 'groups')
    
    def get_department(self, obj):
        return obj.profile.department if hasattr(obj, 'profile') else '-'
    get_department.short_description = '部门'
    
    def get_supervisor(self, obj):
        if hasattr(obj, 'profile') and obj.profile.supervisor:
            return obj.profile.supervisor.username
        return '-'
    get_supervisor.short_description = '上级主管'
    
    def get_queryset(self, request):
        """过滤用户列表：只显示自己和下级的用户"""
        qs = super().get_queryset(request)
        
        # 超级管理员可以看到所有用户
        if request.user.is_superuser:
            return qs
        
        # 获取当前用户的所有下级
        if hasattr(request.user, 'profile'):
            subordinate_users = request.user.profile.get_all_subordinates()
            subordinate_ids = [u.id for u in subordinate_users]
            subordinate_ids.append(request.user.id)  # 包括自己
            return qs.filter(id__in=subordinate_ids)
        
        # 如果没有profile，只能看到自己
        return qs.filter(id=request.user.id)

# 重新注册User模型
admin.site.unregister(User)
admin.site.register(User, CustomUserAdmin)

@admin.register(UserProfile)
class UserProfileAdmin(admin.ModelAdmin):
    """用户扩展信息管理"""
    list_display = ('user', 'department', 'position', 'supervisor', 'phone', 'employee_id')
    list_filter = ('department', 'position')
    search_fields = ('user__username', 'user__email', 'phone', 'employee_id', 'department')
    raw_id_fields = ('user', 'supervisor')
    
    def get_queryset(self, request):
        """过滤用户扩展信息：只显示自己和下级的用户"""
        qs = super().get_queryset(request)
        
        # 超级管理员可以看到所有
        if request.user.is_superuser:
            return qs
        
        # 获取当前用户的所有下级
        if hasattr(request.user, 'profile'):
            subordinate_users = request.user.profile.get_all_subordinates()
            subordinate_ids = [u.id for u in subordinate_users]
            subordinate_ids.append(request.user.id)
            return qs.filter(user__id__in=subordinate_ids)
        
        return qs.filter(user=request.user)

